/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package korekosystem.vista;

import javax.swing.JFrame;
import java.awt.Dimension;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Calendar;
import java.util.HashMap;
import java.text.SimpleDateFormat;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import korekosystem.KorekoSystem;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.swing.JRViewer;

/**
 *
 * @author TOSHIBA
 */
public class balance extends javax.swing.JFrame {

    String mes, anno;
    String PATH;
    Date dato;
    SimpleDateFormat sdf;
    HashMap parametrosMap;
    static Connection conexion;
    
    /**
     * Creates new form balance
     */
    
    public balance() {
        setTheFeel();
        initComponents();
        PATH = "/korekosystem/reportes/";
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField_anno = new javax.swing.JTextField();
        jComboBox_mes = new javax.swing.JComboBox();
        jButton_crear = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Informe Libro Diario");
        setBackground(null);

        jComboBox_mes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre" }));

        jButton_crear.setText("Crear");
        jButton_crear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_crearActionPerformed(evt);
            }
        });

        jLabel1.setText("Año");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox_mes, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField_anno, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton_crear, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(25, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox_mes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField_anno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addComponent(jButton_crear)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void setTheFeel(){
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(compraxmes_prueba.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(compraxmes_prueba.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(compraxmes_prueba.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(compraxmes_prueba.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
    }
        
    private void jButton_crearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_crearActionPerformed
        // TODO add your handling code here:
        mes = jComboBox_mes.getSelectedItem().toString();
        anno = jTextField_anno.getText();
        sdf = new SimpleDateFormat("MMMMM-yyyy");
        
        parametrosMap = new HashMap();
        try {
            dato = sdf.parse(mes + "-" + anno);
            parametrosMap.put("annoMes", dato);
            System.out.println(dato);
            crearConexion();
            crearInforme();
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        } finally {
            cerrarConexion();
        }
    }//GEN-LAST:event_jButton_crearActionPerformed

    private void crearConexion(){
    String driver, urljdbc;

    driver = "com.mysql.jdbc.Driver";
    urljdbc = "jdbc:mysql://212.1.210.181:3306/groupwe_anamaria";
    String user = "groupwe_anamaria";
    String pass = "anamaria";

    conexion = null;

    try{
        Class.forName(driver).newInstance();
        conexion = DriverManager.getConnection(urljdbc,user,pass);
    }
    catch(Exception e){
        e.printStackTrace();
    }

}
    private void cerrarConexion(){
    try{
        if(conexion != null){
            conexion.close();
        }
    }
    catch(SQLException e){
        e.printStackTrace();
    }
}
    
    private void crearInforme(){
        try{
            SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
            JasperReport reporte = (JasperReport)JRLoader.loadObject(KorekoSystem.class.getResourceAsStream(PATH + "reporte-balance.jasper"));

            //Fill the report with parameter, connection and the stream reader (file)
            JasperPrint reportePrint = JasperFillManager.fillReport(reporte, parametrosMap, conexion);

            JRExporter exporter = new JRPdfExporter(); 
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, reportePrint);
            String nombreArchivo = "Libro_Diario-("+ mes + anno + ") " + formato.format(new Date()) + ".pdf";
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(nombreArchivo)); 
            exporter.exportReport();
            
            //Viewer for JasperReport
            JRViewer reportePrintV = new JRViewer(reportePrint);
            //Insert viewer to a JFrame to make it showable
            JFrame jf = new JFrame();
            jf.getContentPane().add(reportePrintV);
            jf.validate();
            jf.setVisible(true);
            jf.setSize(new Dimension(800,600));
            jf.setLocation(300,100);
            jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        }
        catch(JRException e){
            e.printStackTrace();
        }

    }
    /**
     * @param args the command line arguments
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_crear;
    private javax.swing.JComboBox jComboBox_mes;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField_anno;
    // End of variables declaration//GEN-END:variables
}
